import MSData
import WorkerMSAPI
import MSConfig
import MSLogger

import BaseHTTPServer
import time
import datetime
import os
import sys
import pdb

MSLogger.logInit('C:\\Soft\\ms_logs\\ms_webui.contactid.log', 5, True)
reader      = WorkerMSAPI.Worker()
contactid_objects = MSConfig.readObjectsConfig('contactid_objects.cfg')

def parseContactId(raw):
    e = {}
    e['objId']      = raw[2:6]
    e['msgType']    = raw[6:7]
    e['msgCode']    = raw[7:10]
    e['group']      = raw[10:12]
    e['zone']       = raw[12:15]
    return e

def writePage(p, objs):
    p.write('\
        <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"\
            "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">\
        <html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">\
          <head>\
    ')
    p.write('\
          </head>\
          <body>\
    ')
    p.write('<style type="text/css">')
    p.write('td.tblue { color: #000000; background: #ffffff; bordercolor: #808080; font-family: Arial, sans-serif; font-weight: bold; font-size: 12px; border:solid 1 black;}')
    p.write('td.tdblue { color: #000000; background: #bbbbbb; bordercolor: #808080; font-family: Arial, sans-serif; font-weight: bold; font-size: 12px; border:solid 1 black;}')
    p.write('td.tdred {FONT-WEIGHT: bold; FONT-SIZE: 14px; BACKGROUND: pink;  COLOR: #000000; FONT-FAMILY: Arial, sans-serif; }')
    p.write('</style>')
    p.write('<table border="1" style="border-collapse: collapse;">')
    p.write('<tr><td class="tdblue">Date</td><td class="tdblue">Event</td><td class="tdblue">Zone</td><td class="tdblue">Object</td></tr>')


    for o in objs:
        for e in o.eventsContactId:
            e = parseContactId(e.contactIdFull)
            evNum=str(e['msgCode'])+str(e['msgType'])
            if (evNum=='1101'):
                evNum='Pojarnaya trevoga';
            zone=str(e['zone'])
            objId=str(e['objId'])
            evDate=str(datetime.datetime.fromtimestamp(time.time())).split('.')[0]
            p.write('<tr><td class="tblue">%s</td><td class="tblue">%s</td><td class="tblue">%s</td><td class="tblue">%s</td></tr>' % (evDate, evNum,zone,str(o.objectPCNId)))
    p.write('\
          </body>\
        </html>\
    ')


class MyHandler(BaseHTTPServer.BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.end_headers()

        reader.readEventsContactId(contactid_objects)

        writePage(self.wfile, contactid_objects)
        return


if __name__ == '__main__':
    from BaseHTTPServer import HTTPServer
    server = HTTPServer(('localhost', 8080), MyHandler)
#    MSLogger.logInfo('ms online checker started, <Ctrl-C> to stop')
    server.serve_forever()



